const {
    getResult
} = require("./getSendResult")
// 引入处理匹配规则
const {
    pathToRegexp
} = require("path-to-regexp")
const a = require("../util/crypt")
const { patch } = require("./api/getboke")
// 将需要登录成功后才能访问的接口放置在一个数组中
const needTokenApi = [{
        method: "POST",
        path: "/api/userpl/add"
    },
    {
        method:"POST",
        path:"/api/message/add"
    }
]

// path-to-regexp库使用,给一个规则,返回一个正则表达式规则
// const reg = pathToRegexp("/api/student/:id")
// console.log(reg)
// console.log(reg.test("/api/student/1111"))

module.exports = (req, res, next) => {

    // 如果符合规则则直接next,处理匹配规则
    const apis = needTokenApi.filter(api => {
        const reg = pathToRegexp(api.path)
        return api.method === req.method && reg.test(req.path)
    })
    if (apis.length === 0) {
        next()
        return;
    }

    let token = req.cookies.token;
    // let token = req.signedCookies.token;
    if (!token) {
        token = req.headers.authorization;
    }
    if (!token) {
        handleNotToken(req, res, next)
    }

    const userId = a.decrypt(token); //自己写的解密方法
    req.userId = userId //保存到req中,后续操作就知道是哪个管理员操作了
    next()
}

function handleNotToken(req, res, next) {
    res.send(getResult("you dont have any token to access the api"))
}
// 写完以后任何借口都不能访问